import type { Directive, DirectiveBinding } from 'vue'
import { useResizeObserver } from '@vueuse/core'

/**
 * How to use
 * <el-table height="100px" v-el-height-adaptive-table="{bottomOffset: 30}">...</el-table>
 * el-table height is must be set
 * bottomOffset: 30(default)   // The height of the table from the bottom of the page.
 */

interface TableInstance {
  layout: {
    updateElsHeight: () => void
    updateColumnsWidth: () => void
  }
  $el: HTMLElement
  headerWrapper: HTMLElement
}

const doResize = (el: HTMLElement, binding: DirectiveBinding, vnode: any) => {
  const { componentInstance: $table } = vnode

  if (!$table) return

  if (!$table.$ready) {
    $table.$ready = true
    $table.layout.updateElsHeight()
    $table.layout.updateColumnsWidth()
  }

  const { value } = binding

  if (!value) {
    $table.layout.updateElsHeight()
    $table.layout.updateColumnsWidth()
  } else {
    $table.layout.updateElsHeight()
    $table.layout.updateColumnsWidth()
  }
}

const adaptive: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
    const { stop } = useResizeObserver(el, () => {
      doResize(el, binding, vnode)
    })

    el._observer = stop
  },

  updated(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
    doResize(el, binding, vnode)
  },

  unmounted(el: HTMLElement) {
    if (el._observer) {
      el._observer()
      delete el._observer
    }
  }
}

export default adaptive
